package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jaeger.library.StatusBarUtil;
import com.jdew.thkj.R;
import com.jdew.thkj.bean.KeFuWxBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.ActivityManagerUtils;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/4/3 0003.
 */

public class KeFuActivity extends AppCompatActivity implements View.OnClickListener {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.gongzhonghao)
    ImageView gongzhonghao;
    @Bind(R.id.right)
    ImageView right;
    @Bind(R.id.kefu_ercode)
    ImageView kefuErcode;
    @Bind(R.id.kf)
    TextView kf;
    @Bind(R.id.th_wx)
    TextView thWx;
    @Bind(R.id.zhuanshu)
    TextView zhuanshu;
    @Bind(R.id.kefu)
    ImageView kefu;
    @Bind(R.id.kefuhao)
    LinearLayout kefuhao;
    @Bind(R.id.gzhview)
    LinearLayout gzhview;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kefu);
        StatusBarUtil.setTransparentForImageView(this, null);
        ActivityManagerUtils.pushActivity(this);
        ButterKnife.bind(this);
        right.setVisibility(View.GONE);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        initViews();
    }

    public void initViews() {
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        right.setOnClickListener(this);
        title.setText("联系客服");
        gongzhonghao.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Save(gongzhonghao);
                return false;
            }
        });
        kefuErcode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Save(kefuErcode);
                return false;
            }
        });
        kefuhao.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                RegexValidateUtils.copyText(KeFuActivity.this, kf.getText().toString());
                ToastUtils.getInstance(KeFuActivity.this).showMessage("复制成功!");
                return false;
            }
        });
        gzhview.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                RegexValidateUtils.copyText(KeFuActivity.this, thWx.getText().toString());
                ToastUtils.getInstance(KeFuActivity.this).showMessage("复制成功!");
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.right: {
                startActivity(new Intent(this, SubmitErCodeActivity.class));
            }
            break;
            default:
                break;
        }
    }

    public void Save(final ImageView imageView) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage("确定要保存到手机相册吗")
                .setMessageGravity()
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Bitmap bm = createViewBitmap(imageView);
                        RegexValidateUtils.saveBmp2Gallery(KeFuActivity.this,bm);
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    private Bitmap createViewBitmap(View view) {
        // get current view bitmap
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        Bitmap bitmap = view.getDrawingCache(true);
        Bitmap bmp = duplicateBitmap(bitmap);
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        // clear the cache
        view.setDrawingCacheEnabled(false);
        return bmp;
    }

    public static Bitmap duplicateBitmap(Bitmap bmpSrc) {
        if (null == bmpSrc) {
            return null;
        }
        int bmpSrcWidth = bmpSrc.getWidth();
        int bmpSrcHeight = bmpSrc.getHeight();
        Bitmap bmpDest = Bitmap.createBitmap(bmpSrcWidth, bmpSrcHeight, Bitmap.Config.RGB_565);
        if (null != bmpDest) {
            Canvas canvas = new Canvas(bmpDest);
            final Rect rect = new Rect(0, 0, bmpSrcWidth, bmpSrcHeight);
            canvas.drawBitmap(bmpSrc, rect, rect, null);
        }
        return bmpDest;
    }

    @Override
    protected void onResume() {
        super.onResume();
        GetQrCode();
        DisplayQrCode();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManagerUtils.popActivity(this);
    }

    public void GetQrCode() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap<>();
        map.put("Id", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetQrCode(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Id" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<KeFuWxBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(KeFuWxBean bean) {
                if (bean.getCode().equals("0")) {
                    zhuanshu.setText(bean.getData().getUserNice());
                    kf.setText(bean.getData().getWeChatID());
                    kefuErcode.setImageBitmap(null);
                    Glide.with(KeFuActivity.this).load(bean.getData().getQrCodeImgUrl()).into(kefuErcode);
                } else {
                    kefuErcode.setImageDrawable(getResources().getDrawable(R.mipmap.kefu_ercode));
                }
            }
        });
    }

    public void DisplayQrCode() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap<>();
        map.put("Id", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).DisplayQrCode(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Id" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    right.setVisibility(View.VISIBLE);
                } else {
                    right.setVisibility(View.GONE);
                }
            }
        });
    }
}
